import re, os, sys
import shutil

def cpy_and_replace(src, dst, replaces=[]):
    src_file = open(src, 'rb')
    s = src_file.read()
    src_file.close()
    
    for old, new in replaces:
        s = s.replace(old, new)
    
    dst_file = open(dst, 'wb')
    dst_file.write(s)
    dst_file.close()

def get_cfg_path(name, cfg):
    cfg_path = cfg[name].replace('\\', '/')
    if cfg_path[-1] == '/':
        cfg_path = cfg_path[:-1]
    return cfg_path

def init():
    cfg = {}

    try:
        execfile('cfg.txt')
    except:
        print "ERROR:no cfg.txt founded or error!!!"
        return
    
    #cpy_and_replace('.vimrc', 'test.txt', [('D:/WinDDK/7600.16385.0', 'XXXXXXXXXXXXXXXXXXXX')])
    source_path = os.getcwd()
    project_home = get_cfg_path('project_home', cfg)
    wdk_path = get_cfg_path('wdk_path', cfg)
    vim_bin_path = get_cfg_path('vim_bin_path', cfg)
    vim_root_path = os.path.split(vim_bin_path)[0]
    wdk_build_env = cfg['wdk_build_env']
    
    print 'wdk_path->' + wdk_path + '\n' \
          + 'vim_bin_path->' + vim_bin_path + '\n' \
          + 'project_home->' + project_home + '\n' \
          + "!!! setup will del and modify your vim settings!!!\n" \
          "---please backup your vim datas first, then press entry key---\n"
          
    os.system('pause')

    try: os.mkdir('e:/temp')
    except: pass
    
    print 'copy bin files->', vim_bin_path
    cpy_and_replace('cscope.exe', vim_bin_path + '/cscope.exe')
    cpy_and_replace('ctags.exe', vim_bin_path + '/ctags.exe')
    cpy_and_replace('sort.exe', vim_bin_path + '/sort.exe')

    print 'set wdk build env...'
    cpy_and_replace('wdk_build.bat', vim_bin_path + '/wdk_build.bat',
                    [(r'D:\WinDDK\7600.16385.0', wdk_path.replace('/', '\\')),
                     ('chk x64 WIN7', wdk_build_env)])

    print 'copy vimrc & plugins->', vim_root_path
    cpy_and_replace('.vimrc', vim_root_path + '/_vimrc',
                    [('D:/WinDDK/7600.16385.0', wdk_path),
                     ('D:/Documents/Projects', project_home)])
    
    try: shutil.rmtree(vim_root_path + '/vimfiles')
    except: pass
    shutil.copytree('vimfiles', vim_root_path + '/vimfiles')
    
    print 'setup consola font...'
    os.system('copy ' + os.getcwd() + '\\consola.ttf %windir%\\fonts\\>nul 2>nul&' +
              'rundll32.exe gdi32.dll,AddFontResourceA %windir%\\fonts\\consola.ttf')
    
    print 'make initial wdk tags...'
    os.chdir(wdk_path+'/inc/api')
    os.system(source_path + '\\ctags.exe -R --c++-kinds=+p --fields=+iaS --extra=+q .')
    os.chdir(wdk_path+'/inc/ddk')
    os.system(source_path + '\\ctags.exe -R --c++-kinds=+p --fields=+iaS --extra=+q .')

    print 'all done!!!'
    os.system('pause')

if __name__ == '__main__':
    init()
